#!/bin/bash


############## input arguments ##############
db_root_pwd=123456             # database root password
master_ip=198.199.108.10       # master ip
data_dir=$PWD/data             # volume data-dir
c_name=mysql_v1                # container name

############## must edit these ##############
master_file=                   # master status file
master_position=               # master status postion
bin_log_dir=$PWD/binlog        # not last /, not in data_dir
inner_bin_log=/var/log/mysql   # binlog in container
slave_name=slave               # slave name
slave_pwd=abc123               # slave password

############# mkdir for data volume ##########
function prepareDir {
	# mkdir & chmod
    mkdir -p $data_dir 2> /dev/null 
    if [ $? -ne 0 ]; then
    	echo "mkdir $data_dir, permission deny, try add sudo "
        exit 1
    fi
	chmod 777 $data_dir 2> /dev/null
	if [ $? -ne 0 ]; then
		echo "chmod 777 $data_dir, permission deny, try add sudo "
		exit 1
	fi
	mkdir -p $bin_log_dir 2> /dev/null
    if [ $? -ne 0 ]; then
        echo "mkdir $bin_log_dir, permission deny, try add sudo "
        exit 1
    fi
	chmod 777 $bin_log_dir 2> /dev/null;
	if [ $? -ne 0 ]; then
		echo "chmod 777 $bin_log_dir, permission deny, try add sudo "
		exit 1
	fi

	truncate -s 0 conf/my.cnf
	truncate -s 0 init/init.sql
}

############ script usage ###################
function usage {

	if [ -n "$1" ]; then
		echo "error: $1"
	fi

	echo -e "\n*****************************************"
	echo "* usage:"
	# echo "* clean        : $0 clean"
	echo "* start master   : $0 start master "
	echo "* start slave    : $0 start slave {master_ip}"
	echo -e "*******************************************\n"
}

########### start mysql container ###########
function startContainer {
	docker run -ti \
	--name $c_name \
	-v $data_dir:/var/lib/mysql \
	-v $PWD/conf:/etc/mysql/conf.d \
	-v $PWD/init:/docker-entrypoint-initdb.d \
	-v $bin_log_dir:$inner_bin_log \
	-e MYSQL_ROOT_PASSWORD=$db_root_pwd \
	-p 3306:3306 \
	mysql:5.7 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
}


function configMaster {
	#my.cnf
	cat conf/template.txt > conf/my.cnf
	echo -e "\n" >> conf/my.cnf
	echo "log_bin=$inner_bin_log/mysql-bin.log" >> conf/my.cnf
	echo "server-id=$1" >> conf/my.cnf

	#sql init
	cat init/template.txt > init/init.sql
	echo -e "\n" >> init/init.sql
	echo "create user '$slave_name'@'%' identified by '$slave_pwd';" >> init/init.sql
	echo "grant all privileges on *.* to '$slave_name'@'%' identified by '$slave_pwd';" >> init/init.sql
}


###### when slave start, it must have master ip and file and position
function checkSlaveArg {

	if [ -z "$master_ip" ]; then
		echo "master_ip must not empty"
		exit 1
	fi

	if [ -z "$master_file" ] || [ -z "$master_position" ]; then

		if which mysql > /dev/null ; then
			sql_res=`mysql -h$master_ip -uroot -p$db_root_pwd  -ANe "SHOW MASTER STATUS"`
			echo "sql_res $sql_res"
			master_file=`echo $sql_res | awk '{print $1}'`
			master_position=`echo $sql_res | awk '{print $2}'`
			echo $master_file
			echo $master_position
		else
			echo "master_file and master_position must not empty"
			echo "find these 2 value by sql:"
			echo "mysql -h$master_ip -uroot -p$db_root_pwd  -e \"SHOW MASTER STATUS\""
			exit 1
		fi
	fi
}

function configSlave {
	#my.cnf
	cat conf/template.txt > conf/my.cnf
	echo -e "\n" >> conf/my.cnf
	echo "log_bin=$inner_bin_log/mysql-bin.log" >> conf/my.cnf
	echo "server-id=$1" >> conf/my.cnf

	checkSlaveArg
	#sql init
	cat init/template.txt > init/init.sql
	echo -e "\n" >> init/init.sql
	echo "change master to master_host='$master_ip',master_user='$slave_name',master_password='$slave_pwd',master_log_file='$master_file',master_log_pos=$master_position;" >> init/init.sql
	echo "start slave;" >> init/init.sql
}


########### major logic ##########

############ args check
if [ $# -eq 0 ]; then
	usage "too few parameters"
	exit 1;
fi

############
action=$1
# echo "action  : $action"

case "$action" in
	start)
		prepareDir
		if [ $# -lt 2 ]; then
			usage "too few parameters for start"
			exit 1
		fi

		role=$2
		if [ "$role" == "master" ]; then
			# echo "master"
			master_id=${3:-1}         # master id default 1
			if [ -z "$master_id" ]; then
				usage "master_id empty"
				exit 1
			fi
			configMaster $master_id
			startContainer $master_id  
		elif [ "$role" == "slave" ]; then
			# echo "slave"
			slave_id=${3:-2}         # slave id default 2
			if [ -z "$slave_id" ]; then
				usage "slave_id empty"
				exit 1
			fi
			configSlave $slave_id
			#startContainer $slave_id  
		else
			usage "unknown command : $*"
			exit 1
		fi
		;;
	clean)
		docker rm -f $c_name 2> /dev/null
		;;
	build|*)
		usage "unknown command : $*"
		exit 1
		;;
esac
